<template>
  <view class="container">
    <div class="fee-pane-content">
      <ve-form :model="feeForm" ref="formRef" :rules="rules">
        <template v-for="(item, index) in feeForm.orderFee" :key="index">
          <div class="order-fee-item" :class="getCustomClass(item)">
            <div class="order-fee-item-content">
              <fee-pane
                fold
                :orderFeeIndex="index"
                :feeTypeSwitch="false"
                :showViewPriceCalendarBtn="true"
                :disabledOnlineFee="switchFeetypeDisable"
                @feeChange="feeChangeFn"
                @viewPriceCalendar="viewPriceCalendarFn"
              >
                <template #feePaneHeader="{ feeTypeDisabled, feeTypeOptionList }">
                  <ve-form-item class="order-fee-item-name" :borderBottom="false" :label="orderInfo.feeName">
                    <ve-radio v-model="item.feeType" :disabled="feeTypeDisabled" :list="feeTypeOptionList" />
                  </ve-form-item>
                </template>
                <template #returnDepositFee="{ feeOption, showDivider }">
                  <ve-card :title="feeOption.feeName" :showDivider="showDivider">
                    <edit-return-deposit :orderId="orderInfo.orderId" />
                  </ve-card>
                </template>
              </fee-pane>
            </div>
          </div>
        </template>
      </ve-form>
    </div>
    <!-- 底部 footer -->
    <footer-box id="footer-box">
      <template #extra>
        <feeStatistic />
      </template>
      <ve-button type="primary" size="long" :loading="okLoading" @click="submitFn">确认</ve-button>
    </footer-box>
  </view>
</template>
<script setup name="ShortOrderEditFees">
  import { ref, provide, computed } from 'vue'
  import { orderFeeDetailAPI, modifyOrderFeeAPI, calcRateAPI } from '@/api/order/sOrder'
  import feePane from './components/order-fee/fee-pane.vue'
  import footerBox from './form/components/footerBox.vue'
  import feeStatistic from './components/order-fee/fee-statistic.vue'
  import { buildCostInfoParam, initFeeDetail, handleStoreTemplateDetail, getOrderFeeRules } from './components/order-fee/fee-utils.js'
  import editReturnDeposit from './components/return-car/edit-return-deposit.vue'
  import { isValid } from '@/utils'
  import useFormFold from '@/hooks/useFormFold'
  const { foldValidate } = useFormFold([])
  import { onLoad } from '@dcloudio/uni-app'
  import useToast from '@/hooks/useToast'
  import dayjs from 'dayjs'
  // formRef
  const formRef = ref()
  const feeForm = ref({})
  provide('feeForm', feeForm)
  provide('form', feeForm)

  // 订单费用id
  const orderFeeId = ref()
  const orderInfo = ref({})
  provide('orderInfo', orderInfo)
  onLoad((options) => {
    let feeId = options.id
    orderFeeId.value = feeId
    // 费用类型汇总
    // INIT(1, "租车费", true),
    // RERENT(2, "续租", true),
    // ADDITIONAL(3, "额外费用", true),
    // OTHER(4, "其他费用", true),
    // REFUND(5, "退款", true),
    // GIVE_CAR(6, "交车费", true),
    // RETURN_CAR(7, "还车费", true),
    // SERVICE_AMOUNT(8, "增值服务费", true),
    // REPLACE_CAR(9, "换车费", true),
    // CANCEL(10, "取消订单", true),
    // DISCOUNT(11, "优惠费", true),
    // CAR_DEPOSIT(12, "租车押金", false),
    // ILLEGAL_DEPOSIT(13, "违章押金", false),
    // BACK_CAR_DEPOSIT(14, "退租车押金", false),
    // BACK_ILLEGAL_DEPOSIT(15, "退违章押金", false),
    // 16 被违章占用
    // COMPENSATE(17,"赔款",false),
    orderFeeDetailAPI({ id: feeId }).then(({ result }) => {
      orderInfo.value = result
      const feeNameId = result.feeNameId
      let feeDetailTypeList = []
      // 租车费
      switch (feeNameId) {
        case 1:
          feeDetailTypeList = ['basicFee', 'addServiceFee', 'preferentialFee', 'otherFee']
          break
        case 2:
          feeDetailTypeList = ['basicFee', 'addServiceFee', 'preferentialFee', 'otherFee']
          break
        case 3:
          feeDetailTypeList = ['extraFee']
          break
        case 4:
          feeDetailTypeList = ['otherFee']
          break
        case 5:
          feeDetailTypeList = ['refuseFee']
          break
        case 6:
          feeDetailTypeList = ['addServiceFee', 'preferentialFee', 'otherFee']
          break
        case 7:
          feeDetailTypeList = ['extraFee', 'returnRefuseFee', 'returnDepositFee']
          break
        case 8:
          feeDetailTypeList = ['addServiceFee']
          break
        case 9:
          feeDetailTypeList = ['extraFee']
          break
        case 10:
          feeDetailTypeList = ['cancelOrder']
          break
        case 11:
          feeDetailTypeList = ['preferentialFee']
          break
        case 12:
          feeDetailTypeList = ['depositCarRentalFee']
          break
        case 13:
          feeDetailTypeList = ['depositViolationFee']
          break
        case 14:
          feeDetailTypeList = ['returnDepositCarRentalFee']
          break
        case 15:
          feeDetailTypeList = ['returnDepositViolationFee']
          break
        case 17:
          feeDetailTypeList = ['compensateFee']
          break
      }
      // 创建费用时的费用模板快照
      let priceTemplateSnapshot = result.priceTemplateSnapshot
      // 解析后的费用模板
      let storeTemplate = null
      if (priceTemplateSnapshot) {
        priceTemplateSnapshot = JSON.parse(priceTemplateSnapshot)
        storeTemplate = handleStoreTemplateDetail(priceTemplateSnapshot)
      }
      feeForm.value = {
        id: feeId,
        feeNameId: result.feeNameId,
        costType: result.costType,
        feeType: result.feeType,
        feeStatus: result.feeStatus,
        depositDeductFlag: isValid(result.depositDeductionAmount) ? 1 : 0,
        changeDepositFlag: 0,
        orderFee: [
          {
            // 费用类型（线上费用|线下费用）
            feeType: result.feeType,
            feeDetailList: [],
            feeDetailTypeList,
          },
        ],
      }
      let feeValue = feeForm.value
      initFeeDetail(feeValue, storeTemplate)
      // 回显
      // 默认费用
      let feeDetailList = result.feeDetailList
      let formfeeDetailList = feeForm.value.orderFee[0].feeDetailList
      formfeeDetailList.forEach((formFeeDetailItem) => {
        let findResult = feeDetailList.find((item) => {
          let sameFeeCategory = item.feeCategory == formFeeDetailItem.feeCategory
          let sameFeeName = item.itemName == formFeeDetailItem.feeName
          return sameFeeCategory || sameFeeName
        })
        if (findResult) {
          formFeeDetailItem.categoryType = findResult.type
          formFeeDetailItem.id = findResult.id
          formFeeDetailItem.compensateReason = findResult.compensateReason
          if (findResult.type == 1) {
            formFeeDetailItem.remark = result.remark
          } else {
            formFeeDetailItem.remark = findResult.remark
          }
        } else {
          formFeeDetailItem.categoryType = 0
          if (![1, 2, 6, 7].includes(orderInfo.value.feeNameId)) {
            formFeeDetailItem.remark = result.remark
          }
        }
        formFeeDetailItem.childrenList?.forEach((item) => {
          let findFeeDetail = findResult?.childrenList.find((feeDetailItem) => feeDetailItem.itemName == item.itemName)
          if (!findFeeDetail) {
            findFeeDetail = feeDetailList.find((feeDetailItem) => feeDetailItem.itemName == item.itemName)
          }
          if (findFeeDetail && findFeeDetail.itemName == '押金抵扣') {
            findFeeDetail = null
          }
          if (findFeeDetail) {
            // 处理日租价
            if (item.itemName == '车辆租金') {
              let unitPrice = findFeeDetail.unitPrice || 0
              let findResult3 = formFeeDetailItem.childrenList.find((item2) => item2.itemName == '日租价')
              findResult3 && (findResult3.amount = unitPrice)
            }
            item.amount = findFeeDetail.amount
            item.id = findFeeDetail.id
            item.statics = true
            item.costType = findFeeDetail.costType
          }
        })
      })
    })
  })

  const calcRate = ref()
  const getRate = (cb) => {
    if (calcRate.value) {
      cb(calcRate.value)
    } else {
      const param = {
        id: orderFeeId.value,
      }
      calcRateAPI(param).then((res) => {
        const rate = res.result.rate
        calcRate.value = rate
        cb(calcRate.value)
      })
    }
  }
  // 费用变化
  const feeChangeFn = (item, val, index) => {
    let feeDetailList = feeForm.value.orderFee[0].feeDetailList
    let option = feeDetailList[index].childrenList
    let itemName = item.itemName
    if (itemName == '日租价' && isValid(val)) {
      getRate((rate) => {
        let target = option.find((item) => item.itemName == '车辆租金')
        if (target) target.amount = val * rate
      })
    }
  }

  // 线上线下费用是否可以切换
  const switchFeetypeDisable = computed(() => {
    let orderInfoVal = orderInfo.value
    let shortOrderInfoVal = orderInfoVal.shortOrder
    // 费用类型为线下
    if (orderInfoVal.feeType == 1) {
      // 根据接口返回值来判断是否可以切换
      return !shortOrderInfoVal.canAddOnlineFee
    } else {
      // 费用类型为线上
      return shortOrderInfoVal.canModify !== 1
    }
  })

  // computed rules
  const rules = computed(() => {
    let orderFee = feeForm.value.orderFee
    if (orderFee) {
      console.log(orderFee)
      return getOrderFeeRules(orderFee)
    } else {
      return {}
    }
  })
  // 处理数据
  const handleOption = (option) => {
    let feeDetailList = []
    // 处理 remark
    if (![1, 2, 6, 7].includes(orderInfo.value.feeNameId)) {
      let remark
      for (let i = 0; i < option.feeDetailList.length; i++) {
        let item = option.feeDetailList[i]
        remark = item.remark
      }
      option.remark = remark
    }
    for (let i = 0; i < option.feeDetailList.length; i++) {
      let item = option.feeDetailList[i]
      if (item.type == 1) {
        let childrenList = item.childrenList
        if (childrenList?.length > 0) {
          for (let j = childrenList?.length - 1; j >= 0; j--) {
            let tempItem = {
              ...childrenList[j],
              compensateReason: item.compensateReason,
              type: 1,
              feeCategory: item.feeCategory,
            }
            option.feeDetailList.splice(i + 1, 0, tempItem)
          }
          option.feeDetailList.splice(i, 1)
          i--
        }
      }
    }
    option.feeDetailList.forEach((item) => {
      if (item.type == 1) {
        let originFeeDetailList = orderInfo.value.feeDetailList
        let orignItem = originFeeDetailList.find((originItem) => originItem.itemName == item.itemName)
        feeDetailList.push({
          ...item,
          id: orignItem ? orignItem.id : undefined,
        })
      } else {
        feeDetailList.push(item)
      }
    })
    option.feeDetailList = feeDetailList
    return option
  }
  const getCustomClass = (item) => {
    let feeDetailList = item.feeDetailList
    let extraClass = ''
    if (feeDetailList) {
      for (let i = 0; i < feeDetailList.length; i++) {
        let feeItem = feeDetailList[i]
        if (feeItem.type == 'addServiceFee') {
          let childrenList = feeItem.childrenList || []
          if (childrenList.some((feeDetailItem) => feeDetailItem.statics)) {
            extraClass = 'order-fee-item-add-service-fee'
            break
          }
        }
      }
    }
    return extraClass
  }
  // 查看价格日历
  const viewPriceCalendarFn = () => {
    const info = orderInfo.value
    const startTime = info.shortOrder.startTime
    const priceModelName = info.shortOrder.originalModelName
    const priceModelId = info.priceModelId
    let start = dayjs(startTime).startOf('month').format('YYYY-MM-DD HH:mm:ss')
    uni.navigateTo({
      url: `/pages/order/price-calendar?priceModelName=${priceModelName}&priceModelId=${priceModelId}&start=${start}`,
    })
  }
  const okLoading = ref(false)
  const submitFn = () => {
    new Promise((resolve) => {
      if (rules.value && Object.keys(rules.value).length > 0) {
        formRef.value.validate((valid, errors) => {
          console.log(valid)
          if (valid) {
            resolve()
          } else {
            foldValidate(errors, true)
          }
        })
      } else {
        resolve()
      }
    }).then(() => {
      let feeFormValue = feeForm.value
      let { orderFee } = buildCostInfoParam(feeFormValue)
      // 处理 option
      let option = handleOption(orderFee[0])
      const param = {
        ...option,
        id: feeFormValue.id,
        feeNameId: feeFormValue.feeNameId,
        costType: feeFormValue.costType,
        feeStatus: feeFormValue.feeStatus,
      }
      // 编辑还车费
      if (orderInfo.value.feeNameId == 7) {
        param.depositDeductFlag = feeFormValue.depositDeductFlag
        param.depositDeductAmount = feeFormValue.depositDeductAmount
        param.changeDepositFlag = feeFormValue.changeDepositFlag
        param.changeDepositAmount = feeFormValue.changeDepositAmount
      }
      delete param.priceTemplateId
      okLoading.value = true
      modifyOrderFeeAPI(param)
        .then(() => {
          useToast({
            title: '修改成功',
          }).then(() => {
            uni.$emit('success')
            uni.navigateBack({
              delta: 1,
            })
          })
        })
        .catch(() => {
          okLoading.value = false
        })
    })
  }
</script>
<style lang="less" scoped>
  .container {
    flex-direction: column;
    .fee-pane-content {
      flex: 1;
      overflow: auto;
      padding-bottom: 260rpx;
    }
    #footer-box {
      height: 250rpx;
      position: fixed;
      bottom: 0;
      background-color: #ffffff;
      z-index: 100;
    }
  }
  .fee-pane-content {
    padding: 24rpx;
  }
  .order-fee-item {
    :deep(.add-service-fee .ve-card-content) {
      padding-top: 32rpx;
      padding-bottom: 8rpx;
    }
    :deep(.generic-fee .ve-card-content) {
      padding-top: 0rpx;
      padding-bottom: 8rpx;
    }
  }
  .order-fee-item-add-service-fee {
    :deep(.add-service-fee .ve-card-content) {
      padding-bottom: 32rpx;
    }
  }
  .order-fee-item-name {
    background: #ffffff;
    border-radius: 8rpx 8rpx 8rpx 8rpx;
    padding: 0 28rpx;
    /deep/ .ve-form-item__body__left__content__label {
      font-size: 30rpx;
      color: #191c27;
    }
    /deep/ .ve-form-item__body__right {
      position: relative;
      top: 8rpx;
      .radio .title {
        margin-right: 40rpx;
      }
      .radio .title:last-child {
        margin-right: 0;
      }
    }
  }

  /deep/ .ve-form-item[disabled='true'] {
    color: #cdced0;
    .ve-form-item__body__right__content__unit {
      color: #cdced0;
    }
  }
</style>
